﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Cart.Models;
using Web.Core.Models;
using Web.Core.Security;
using Web.Core.ActionFilters;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;

namespace Web.Cart.Controllers
{
    [Auth(UserRole.Buyer)]
    public class CheckoutController : BaseController
    {
        public CheckoutController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        public ActionResult Index(byte? param, ShoppingCart cart)
        {
            var userId = User.Identity.Identity().Id;
            var model = new CheckoutControllerModel.Index();
            if (cart.UserAddress == null)
            {
                model.Param = 0;
                var addresses = UserAddressList(userId);
                var address = addresses.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                if (address != null)
                {
                    if (address.Province.IsNullOrEmpty() || address.City.IsNullOrEmpty() || address.District.IsNullOrEmpty())
                    {
                        var areas = AreaFullName(address.AreaId, AreaList());
                        address.Province = areas.First;
                        address.City = areas.Second;
                        address.District = areas.Third;
                    }
                    cart.UserAddress = address;
                }
            }
            if (param.HasValue && param.Value == 1)
            {
                model.Param = 1;
                var addresses = Passport.Value.UserAddressList(userId);
                model.UserAddresses = addresses;
            }
            if (ShoppingCart.Config.InvoiceEnabled)
            {
                if (cart.UserInvoice == null)
                {
                    model.Param = 2;
                    var invoices = Passport.Value.UserInvoiceList(userId);
                    var invoice = invoices.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                    cart.UserInvoice = invoice;
                }
                if (param.HasValue && param.Value == 3)
                {
                    model.Param = 3;
                    var invoices = Passport.Value.UserInvoiceList(userId);
                    model.UserInvoices = invoices;
                }
            }
            cart.Postage = 10;
            model.ShoppingCart = cart;
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(byte? param, ShoppingCart cart, UserAddress userAddress, UserInvoice userInvoice)
        {
            var identity = User.Identity.Identity();

            var result = new MagicKit<string>();
            if (param.HasValue && param.Value.IsIn(new byte[] { 0, 1 }) && userAddress != null)
            {
                userAddress.UserId = identity.Id;
                userAddress.Country = 86;
                userAddress.CreatedBy = User.Identity.Name;
                userAddress.Category = AddressCategory.Receive;
                var areas = AreaFullName(userAddress.AreaId, AreaList());
                userAddress.Province = areas.First;
                userAddress.City = areas.Second;
                userAddress.District = areas.Third;

                cart.UserAddress = userAddress;

                result.Status = true;
                return Json(result);
            }
            if (param.HasValue && param.Value.IsIn(new byte[] { 2, 3 }) && ShoppingCart.Config.InvoiceEnabled &&
                userInvoice != null)
            {
                userInvoice.UserId = identity.Id;

                userInvoice.CreatedBy = User.Identity.Name;

                cart.UserInvoice = userInvoice;

                result.Status = true;
                return Json(result);
            }
            if (cart.UserAddress != null && cart.Items.Count > 0)
            {
                var order = cart.ToOrder(GetIpAddress());
                var magic = Trade.Value.OrderCreate(order);
                var status = result.Status = magic.Status;
                if (status)
                {
                    result.Data = order.Id;
                    Session[ShoppingCart.SessionKey] = null;
                }
                else
                {
                    result.Message = magic.Message;
                }
            }
            return Json(result);
        }

    }
}
